package com.common.frame.utils;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;


import com.common.frame.bean.PermissionResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.SingleSubject;

/**
 * - 请求权限并接受返回值。
 * Created by Sunxy
 */
public class PermissionForResultUtils extends Fragment {

    private SingleSubject<PermissionResult> mSubject;
    private int startRequestCode;
    private ArrayList<String> deniedPermission = new ArrayList<>();
    private ArrayList<String> deniedPermissionExplain = new ArrayList<>();
    private Map<String, String> permissionsExplainMap = new HashMap<>();
    private boolean mustHave;
    private Disposable dis;

    public static PermissionForResultUtils getFragment(Fragment fragment){
        return generateFragment(fragment.getChildFragmentManager());
    }

    public static PermissionForResultUtils getFragment(AppCompatActivity activity){
        return generateFragment(activity.getSupportFragmentManager());
    }

    private static PermissionForResultUtils generateFragment(FragmentManager fragmentManager){
        if (fragmentManager == null){
            return new PermissionForResultUtils();
        }
        PermissionForResultUtils fragment = (PermissionForResultUtils) fragmentManager.findFragmentByTag("PermissionForResultUtils");
        if (fragment == null){
            fragment = new PermissionForResultUtils();
            fragmentManager.beginTransaction().add(fragment, "PermissionForResultUtils").commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
        return fragment;
    }

    /**
     * 请求权限。
     */
    public Single<PermissionResult> request(final String... permissions) {
        mustHave = false;
        return start(permissions, null);
    }

    /**
     * 请求权限
     * 如果用户禁止则会一直请求。直到用户同意权限 或者 点击不再提示并禁止。
     */
    public Single<PermissionResult> requestMustHave(final String... permissions) {
        mustHave = true;
        return start(permissions, null);
    }

    /**
     * 请求权限
     * 如果用户禁止则会一直请求。直到用户同意权限 或者 点击不再提示并禁止。
     * @param permissions           请求的权限数组
     * @param permissionsExplain    权限说明数组
     */
    public Single<PermissionResult> requestMustHave(String[] permissions, String[] permissionsExplain) {
        mustHave = true;
        return start(permissions, permissionsExplain);
    }


    private Single<PermissionResult> start(String[] permissions, String[] permissionsExplain) {

        if (dis != null && !dis.isDisposed()) dis.dispose();
        permissionsExplainMap.clear();
        if (permissions != null && permissionsExplain != null && permissions.length == permissionsExplain.length){
            for (int i = 0; i < permissions.length; i++) {
                permissionsExplainMap.put(permissions[i], permissionsExplain[i]);
            }
        }
        this.startRequestCode = new Random().nextInt(1000) + 10000;
        mSubject = SingleSubject.create();
        return mSubject.doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                dis = disposable;
                requestPermissions(permissions, startRequestCode);
            }
        }).observeOn(AndroidSchedulers.mainThread());
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dis != null && !dis.isDisposed()) dis.dispose();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == startRequestCode){
            deniedPermission.clear();
            deniedPermissionExplain.clear();
            for (int i = 0; i < permissions.length; i++) {
                int result = grantResults[i];
                String permission = permissions[i];
                if (result != PackageManager.PERMISSION_GRANTED) {
                    if (mustHave){
                        if (!shouldShowRequestPermissionRationale(permission)){
                            // 禁止权限，并选中【禁止后不再询问】
                            deniedPermissionExplain.add(getPermissionsExplain(permission));
                        }else{
                            deniedPermission.add(permission);
                        }
                    }else{
                        deniedPermissionExplain.add(getPermissionsExplain(permission));
                    }
                }
            }

            if (!deniedPermission.isEmpty()){
                requestPermissions(deniedPermission.toArray(new String[deniedPermission.size()]), startRequestCode);
                return;
            }

            if (deniedPermissionExplain.isEmpty()){
                mSubject.onSuccess(new PermissionResult(Activity.RESULT_OK, deniedPermissionExplain));
            }else{
                mSubject.onSuccess(new PermissionResult(Activity.RESULT_CANCELED, deniedPermissionExplain));
            }

        }
    }

    private String getPermissionsExplain(String permission){
        String permissionsStr = permissionsExplainMap.get(permission);
        if (TextUtils.isEmpty(permissionsStr)){
            permissionsStr = permission;
        }
        return permissionsStr;
    }
}
